import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-05
 * Time: 17:21
 */
public class Main {
    private static String dirPath = "./";
    private static String filePath = "append.txt";
    private static String fromPath = "from.JPG";
    private static String toPath = "to.JPG";

    /**
     *  将一张图片复制到其他位置
     */
    public static void copyPicture(String fromPath, String toPath) throws IOException {
        File fromFile = new File(fromPath);
        File toFile = new File(toPath);
        FileInputStream inputStream = new FileInputStream(fromFile);
        FileOutputStream outputStream = new FileOutputStream(toFile);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }


    /**
     *  打印一个文件夹下面所有文件的名字
     * @param file
     * @throws IOException
     */
    public static void printAllFile(File file) throws IOException {
        if (!file.exists()) {
            return ;
        }
        // 是文件夹
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            // 文件夹里面没有内容
            if (files == null || files.length == 0) {
                return ;
            }
            for (File f: files) {
                // 是文件夹继续递归
                if (f.isDirectory()) {
                    printAllFile(f);
                } else {
                    // 是文件, 直接打印文件名
                    System.out.println(f.getCanonicalPath());
                }
            }
        } else {
            // 是文件, 直接打印文件名
            System.out.println(file.getCanonicalPath());
        }
    }

    /**
     *  对文件内容进行追加操作
     * @param file
     * @throws IOException
     */
    public static void fileAppend(File file) throws IOException {
        // 注意第二个参数写上 true, 这样才是文件追加, 而不是覆盖
        FileWriter writer = new FileWriter(file, true);
        // 即使使用 append , 但是writer 的第二个参数不是 true, 仍然是覆盖操作
        writer.append("你好! 世界! ");
        writer.close();
    }

    public static void main(String[] args) throws IOException {
        copyPicture(fromPath, toPath);
        File file1 = new File(dirPath);
        printAllFile(file1);
        File file2 = new File(filePath);
        fileAppend(file2);
    }
}
